package com.example.oss.message;

import com.alibaba.fastjson.JSON;
import com.example.oss.entity.Course;
import com.example.oss.entity.Message;
import com.example.oss.entity.Order;
import com.example.oss.service.CourseService;
import com.example.oss.service.OrderService;
import com.example.oss.util.RedisKeyUtil;
import com.example.oss.util.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

//@Component
@Slf4j
public class MessageReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CourseService courseService;


//    @RabbitListener(queues = "placeAnOrder")
    public void receiverSelectCourseMessage(String message) {
        if (StringUtils.isBlank(message)) {
            log.error("消息为空！");
            return;
        }
        Message messageEntity = JSON.parseObject(message, Message.class);
        if (messageEntity == null) {
            log.error("消息格式不正确！");
            return;
        }
        int stuId = messageEntity.getStuId();
        int courseId = messageEntity.getCourseId();

        //DB验重
        if (orderService.existStuId(stuId)) {
            return;
        }
        //DB验库存
        if (courseService.getCourseByIdFromDB(courseId).getAmount() < 1) {
            return;
        }
        //订单入库
        Order order = orderService.order(courseId, stuId);
        if (order != null) {
            log.info("订单入库成功！");
        } else {
            log.error("订单入库出现异常！");
            return;
        }
        ThreadPoolUtil.executorService.execute(() -> {
            //DB下单成功，异构订单信息到缓存中，以提供我的订单中查询
            try {
                Course course = courseService.getCourseByIdFromDB(order.getCourseId());
                Map map = JSON.parseObject(JSON.toJSONString(course), Map.class);
                redisTemplate.opsForHash().putAll(RedisKeyUtil.getOrderKey(stuId), map);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("订单信息异构到缓存失败！");
            }
        });

    }
}
